import { useState, useEffect } from 'react';
import { Layout, Menu, theme, Avatar, Dropdown, Button, Space } from 'antd';
import { 
  ShopOutlined, 
  OrderedListOutlined, 
  UserOutlined, 
  LogoutOutlined, 
  ShoppingOutlined, 
  DashboardOutlined
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import axios from 'axios';
import { MenuProps } from 'antd';




type MenuItem = Required<MenuProps>['items'][number];


const { Header, Content, Sider } = Layout;

interface MerchantInfo {
  name: string;
  avatar?: string;
}

export default function MerchantLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const [merchantInfo, setMerchantInfo] = useState<MerchantInfo>({ name: '加载中...' });
  const navigate = useNavigate();
  const location = useLocation();
  
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  // 获取商家信息
  useEffect(() => {
    const fetchMerchantInfo = async () => {
      try {
        const response = await axios.get('/api/merchant/profile');
        setMerchantInfo(response.data);
      } catch (error) {
        console.error('获取商家信息失败:', error);
        setMerchantInfo({ name: 'test' });
      }
    };

    fetchMerchantInfo();
  }, []);

  // 确定当前选中的菜单项
  const getSelectedKey = () => {
    if (location.pathname.includes('/merchant/dashboard')) {
      return ['1'];
    }
    else if (location.pathname.includes('/merchant/products')) {
      return ['2'];
    } else if (location.pathname.includes('/merchant/orders')) {
      return ['3'];
    }
    return ['1'];
  };


  // 左侧菜单
  const menuItems: MenuItem[] = [
    {
      key: '1',
      icon: <DashboardOutlined />,
      label: '仪表盘',
      onClick: () => navigate('/merchant/dashboard')
    },
    {
      key: '2',
      icon: <ShopOutlined />,
      label: '商品管理',
      onClick: () => navigate('/merchant/products')
    },
    {
      key: '3',
      icon: <OrderedListOutlined />,
      label: '订单处理',
      onClick: () => navigate('/merchant/orders')
    }
  ];

  // 用户下拉菜单
  const userMenu = {
    items: [
      {
        key: '1',
        icon: <UserOutlined />,
        label: '商家信息',
        onClick: () => navigate('/merchant/profile')
      },
      {
        key: '2',
        icon: <LogoutOutlined />,
        label: '退出登录',
        onClick: () => {
        
          localStorage.removeItem('merchantToken');
          navigate('/login');
        }
      }
    ]
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider 
        collapsible 
        collapsed={collapsed} 
        onCollapse={(value) => setCollapsed(value)}
      >
        <div className="flex items-center justify-center h-16 bg-primary text-white">
          <h2 className={`text-lg font-bold ${collapsed ? 'hidden' : 'block'}`}>商家管理面板</h2>
          {collapsed && <ShopOutlined style={{ fontSize: '24px' }} />}
        </div>
        <Menu 
          theme="dark" 
          defaultSelectedKeys={getSelectedKey()} 
          selectedKeys={getSelectedKey()}
          mode="inline" 
          items={menuItems} 
        />


      </Sider>

      
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }} className="flex justify-between items-center px-6">
          {/* <div className="text-lg font-bold">
            {location.pathname.includes('/merchant/products') ? '商品管理' : '订单处理'}
          </div> */}
          <div></div>
          <div className="flex items-center mr-10">
            <Button 
              type="link" 
              icon={<ShoppingOutlined />} 
              onClick={() => navigate('/')}
              className="mr-4"
            >
              返回购物
            </Button>
            <Dropdown menu={userMenu} placement="bottomRight">
              <Space className="cursor-pointer ">
                <Avatar 
                  src={merchantInfo.avatar} 
                  icon={!merchantInfo.avatar && <UserOutlined />} 
                  size="default" 
                />
                <span className="hidden md:inline">{merchantInfo.name}</span>
              </Space>
            </Dropdown>
          </div>
        </Header>
        <Content style={{ margin: '16px' }}>
          <div
            style={{
              padding: 24,
              minHeight: 360,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

